package test

import (
	"chat_gin/utils"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
	"time"
)

// 防止跨域站点伪造请求
var upGrade = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return false
	},
}

func SendMsg(c *gin.Context) {
	ws, err := upGrade.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		fmt.Println("错误", err)
		return
	}
	defer func(ws *websocket.Conn) {
		err = ws.Close()
		if err != nil {
			fmt.Println("关闭ws失败", err)
		}
	}(ws)

	// 这里要写一个for循环调用
	MsgHandler(ws, c)
}

func MsgHandler(ws *websocket.Conn, c *gin.Context) {
	msg, err := utils.Subscribe(c, utils.PUblishKey)
	if err != nil {
		return
	}
	nowTime := time.Now().Format("2006-01-02 15:04:05")
	fmt.Println(nowTime)
	fmt.Println("时间", nowTime, "==消息==", msg)
	m := fmt.Sprintf("[ws][%s]:%s", nowTime, msg)
	err = ws.WriteMessage(1, []byte(m))
	if err != nil {
		fmt.Println("提升错误", err)
	}
}
